
import sys, os, subprocess, getpass, pycurl, urllib.parse
if __name__ == "__main__":
    def get_proxy():
        proxy = ""
        if "http_proxy" in os.environ:
            proxy = os.environ["http_proxy"]
        elif "https_proxy" in os.environ:
            proxy = os.environ["https_proxy"]
        host = proxy[proxy.rfind('/') + 1: proxy.rfind(':')]
        port = proxy[proxy.rfind(':') + 1:]
        foo = proxy.find("socks://") >= 0 or proxy.find("socks5h://")
        return host, int(port), foo

    def api_upload(endpoint, dest_fmt = "/microblog/%s"):
        pages = []
        with open("updatedfiles.txt") as f:
            pages = f.readlines()
        c = pycurl.Curl()

        if "http_proxy" in os.environ or "https_proxy" in os.environ:
            hostname, port_no, is_socks = get_proxy()
            c.setopt(pycurl.PROXY, hostname)
            c.setopt(pycurl.PROXYPORT, port_no)
            if is_socks:
                c.setopt(pycurl.PROXYTYPE, pycurl.PROXYTYPE_SOCKS5_HOSTNAME)

        c.setopt(c.URL, endpoint)
        c.setopt(c.POST, 1)
        for page in pages:
            p = page.strip('\n')
            #i = p.rfind('/')
            # folder = p[1:i]
            # file   = p[i]
            destination = dest_fmt % p
            source = p
            print("sending @%s to %s" % (source, destination))
            exists = True
            try:
                with open(source, 'r') as f:
                    pass
            except FileNotFoundError as e:
                exists = False
                print(e)
            if (exists):
                c.setopt(c.HTTPPOST, [(destination, (c.FORM_FILE, source))])
                try:
                    c.perform()
                except pycurl.error as e:
                    print(e)
        c.close()

    def main():
        if len(sys.argv) < 2:
            print("Usage: neouploader.py [neocities username]")
            return
        try:
            pw = getpass.getpass(prompt="Password: ")
        except KeyboardInterrupt:
            print("Aborted.")
            return
        if len(pw) == 0:
            print("Empty input. Exiting.")
            return
        p = urllib.parse.quote(pw, safe='')
        target = "https://%s:%s@neocities.org/api/upload" % (sys.argv[1], p)
        del pw
        del p
        api_upload(target)
        del target
    main()
